<template>
  <div class="merchandise-product-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>周边商品管理</h2>
      <p>管理所有周边商品信息，包含详细商品属性</p>
    </div>

    <!-- 操作区 -->
    <div class="operation-area">
      <el-button type="primary" @click="showAddDialog">
        <i class="el-icon-plus"></i> 新增商品
      </el-button>

      <el-input
        v-model="searchKeyword"
        placeholder="搜索商品名称或类型"
        style="width: 300px; margin-left: 10px;"
        prefix-icon="el-icon-search"
        @keyup.enter.native="handleSearch"
      ></el-input>
    </div>

    <!-- 排序工具栏 -->
    <div class="toolbar">
      <div class="sort">
        <span>排序方式:</span>
        <select v-model="sortBy" @change="handleSortChange">
          <option value="featured">推荐商品</option>
          <option value="price_asc">价格从低到高</option>
          <option value="price_desc">价格从高到低</option>
          <option value="created_at_desc">最新上架</option>
        </select>
      </div>
    </div>

    <!-- 商品列表 -->
    <el-table
      :data="filteredProducts"
      border
      style="width: 100%; margin-top: 15px;"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>

      <el-table-column label="商品图片" width="120">
        <template slot-scope="scope">
          <el-image
            :src="scope.row.image_urls && scope.row.image_urls.length > 0
              ? (scope.row.image_urls[0].startsWith('http') ? scope.row.image_urls[0] : `http://127.0.0.1:8000/static/${scope.row.image_urls[0]}`)
              : ''"
            :preview-src-list="scope.row.image_urls ? scope.row.image_urls.map(img =>
              img.startsWith('http') ? img : `http://127.0.0.1:8000/static/${img}`) : []"
            style="width: 80px; height: 80px; object-fit: cover;"
            placeholder="暂无图片"
          ></el-image>
        </template>
      </el-table-column>

      <el-table-column prop="name" label="商品名称" min-width="180"></el-table-column>

      <el-table-column prop="category_name" label="商品分类" width="120"></el-table-column>

      <el-table-column label="价格" min-width="180">
        <template slot-scope="scope">
          <span class="original-price" v-if="scope.row.original_price">¥{{ scope.row.original_price.toFixed(2) }}</span>
          <span class="current-price">¥{{ scope.row.price.toFixed(2) }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="stock" label="库存" width="100"></el-table-column>

      <el-table-column prop="is_active" label="状态" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.is_active"
            active-color="#8B5A2B"
            inactive-color="#f0e9e0"
            @change="handleStatusChange(scope.row)"
            :disabled="statusChanging.includes(scope.row.id)"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="推荐" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.is_featured"
            active-color="#8B5A2B"
            inactive-color="#f0e9e0"
            @change="handleRecommendChange(scope.row)"
            :disabled="statusChanging.includes(scope.row.id)"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="showEditDialog(scope.row)"
            class="edit-btn"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            @click="confirmDelete(scope.row.id)"
            class="delete-btn"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <button class="pagination-btn" @click="prevPage" :disabled="currentPage === 1 || loading">
        <i class="arrow-icon">&lt;</i>
      </button>
      <button
        v-for="page in totalPages"
        :key="page"
        class="pagination-btn"
        :class="{ 'active': currentPage === page }"
        @click="goToPage(page)"
        :disabled="loading"
      >
        {{ page }}
      </button>
      <button class="pagination-btn" @click="nextPage" :disabled="currentPage === totalPages || loading">
        <i class="arrow-icon">&gt;</i>
      </button>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
    >
      <el-form :model="form" label-width="100px" class="form-container" ref="productForm">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称"></el-input>
        </el-form-item>

        <el-form-item label="商品图片">
          <el-input v-model="imageUrl" placeholder="请输入图片URL，多个URL用逗号分隔"></el-input>
          <div class="image-preview" v-if="form.image_urls && form.image_urls.length">
            <el-image
              v-for="(img, index) in form.image_urls"
              :key="index"
              :src="img.startsWith('http') ? img : `http://127.0.0.1:8000/static/${img}`"
              style="width: 100px; height: 100px; object-fit: cover; margin-right: 10px;"
            ></el-image>
          </div>
        </el-form-item>

        <el-form-item label="商品分类" prop="category_id">
          <el-select v-model="form.category_id" placeholder="请选择分类">
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="原价" prop="original_price">
          <el-input v-model="form.original_price" type="number" placeholder="请输入原价"></el-input>
        </el-form-item>

        <el-form-item label="现价" prop="price">
          <el-input v-model="form.price" type="number" placeholder="请输入现价"></el-input>
        </el-form-item>

        <el-form-item label="库存" prop="stock">
          <el-input v-model="form.stock" type="number" placeholder="请输入库存数量"></el-input>
        </el-form-item>

        <el-form-item label="是否推荐">
          <el-switch
            v-model="form.is_featured"
            active-color="#8B5A2B"
            inactive-color="#f0e9e0"
          ></el-switch>
        </el-form-item>

        <el-form-item label="是否上架">
          <el-switch
            v-model="form.is_active"
            active-color="#8B5A2B"
            inactive-color="#f0e9e0"
          ></el-switch>
        </el-form-item>

        <el-form-item label="商品描述">
          <el-input v-model="form.description" type="textarea" rows="4" placeholder="请输入商品描述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProduct" :loading="saveLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 删除确认 -->
    <el-dialog
      title="提示"
      :visible.sync="deleteDialogVisible"
      width="300px"
    >
      <p>确定要删除该商品吗？</p>
      <div slot="footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="doDelete" :loading="deleteLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api/request'

export default {
  name: 'MerchandiseProductManagement',
  data() {
    return {
      // 商品数据
      products: [],
      filteredProducts: [],
      categories: [],

      // 加载状态
      loading: false,
      saveLoading: false,
      deleteLoading: false,
      statusChanging: [],

      // 搜索和分页
      searchKeyword: '',
      currentPage: 1,
      pageSize: 10,
      totalPages: 1,
      totalItems: 0,

      // 排序
      sortBy: 'featured',
      sortField: 'created_at',
      sortOrder: 'desc',

      // 弹窗状态
      dialogVisible: false,
      deleteDialogVisible: false,
      dialogTitle: '新增商品',
      currentId: null,

      // 表单数据
      form: {
        name: '',
        image_urls: [],
        category_id: null,
        description: '',
        price: null,
        original_price: null,
        stock: 0,
        is_featured: false,
        is_active: true
      },
      imageUrl: ''
    }
  },
  created() {
    this.fetchCategories()
    this.getProductsByPage()
  },
  methods: {
    // 获取分类列表
    async fetchCategories() {
      try {
        const response = await api.get('/merchandiseCategory')
        if (response.code === 200) {
          this.categories = response.data
        }
      } catch (error) {
        console.error('获取分类失败:', error)
        this.$message.error('获取分类失败，请刷新页面重试')
      }
    },

    // 获取分页数据
    async getProductsByPage() {
      this.loading = true
      try {
        const response = await api.get('/merchandiseProduct/page', {
          params: {
            page: this.currentPage,
            limit: this.pageSize,
            sort_by: this.sortField,
            sort_order: this.sortOrder
          }
        })

        if (response.code === 200) {
          this.products = response.data.merchandise_products
          this.filteredProducts = [...this.products]
          this.totalPages = response.data.pagination.total_pages
          this.totalItems = response.data.pagination.total
          this.sortField = response.data.pagination.sort_by
          this.sortOrder = response.data.pagination.sort_order
        }
      } catch (error) {
        console.error('获取商品列表错误:', error)
        this.$message.error('获取商品列表失败，请刷新页面重试')
      } finally {
        this.loading = false
      }
    },

    // 搜索商品
    handleSearch() {
      if (!this.searchKeyword) {
        this.filteredProducts = [...this.products]
        return
      }

      const keyword = this.searchKeyword.toLowerCase()
      this.filteredProducts = this.products.filter(item =>
        item.name.toLowerCase().includes(keyword) ||
        (item.category_name && item.category_name.toLowerCase().includes(keyword))
      )
    },

    // 处理排序变化
    handleSortChange() {
      switch(this.sortBy) {
        case 'price_asc':
          this.sortField = 'price'
          this.sortOrder = 'asc'
          break
        case 'price_desc':
          this.sortField = 'price'
          this.sortOrder = 'desc'
          break
        case 'created_at_desc':
          this.sortField = 'created_at'
          this.sortOrder = 'desc'
          break
        case 'featured':
        default:
          this.sortField = 'created_at'
          this.sortOrder = 'desc'
      }
      this.currentPage = 1
      this.getProductsByPage()
    },

    // 分页方法
    goToPage(page) {
      if (page < 1 || page > this.totalPages || page === this.currentPage) return
      this.currentPage = page
      this.getProductsByPage()
    },

    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
        this.getProductsByPage()
      }
    },

    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++
        this.getProductsByPage()
      }
    },

    // 显示新增弹窗
    showAddDialog() {
      this.dialogTitle = '新增周边商品'
      this.currentId = null
      this.form = {
        name: '',
        image_urls: [],
        category_id: null,
        description: '',
        price: null,
        original_price: null,
        stock: 0,
        is_featured: false,
        is_active: true
      }
      this.imageUrl = ''
      this.dialogVisible = true
    },

    // 显示编辑弹窗
    showEditDialog(row) {
      this.dialogTitle = '编辑周边商品'
      this.currentId = row.id
      this.form = JSON.parse(JSON.stringify(row))
      this.imageUrl = this.form.image_urls ? this.form.image_urls.join(',') : ''
      this.dialogVisible = true
    },

    // 保存商品
    async saveProduct() {
      // 基本表单验证
      if (!this.form.name || !this.form.category_id || this.form.price === null) {
        this.$message.warning('请填写必填字段')
        return
      }

      // 处理图片URL
      if (this.imageUrl) {
        this.form.image_urls = this.imageUrl.split(',').map(url => url.trim())
      } else {
        this.form.image_urls = []
      }

      this.saveLoading = true
      try {
        let response
        if (this.currentId) {
          // 编辑商品
          response = await api.put(`/merchandiseProduct/${this.currentId}`, this.form)
        } else {
          // 新增商品
          response = await api.post('/merchandiseProduct', this.form)
        }

        // 检查响应是否成功
        if (response && (response.code === 200 || response.success)) {
          if (this.currentId) {
            this.$message.success('商品修改成功')
          } else {
            this.$message.success('商品新增成功')
          }
          this.dialogVisible = false
        } else {
          this.$message.error(response?.message || '操作失败，请重试')
        }
      } catch (error) {
        console.error('保存商品错误:', error)
        // 只在真正发生错误时显示错误提示
        if (error && error.response) {
          this.$message.error(`操作失败: ${error.response.data?.message || '服务器错误'}`)
        }
      } finally {
        // 无论成功与否都刷新页面数据
        this.getProductsByPage()
        this.saveLoading = false
      }
    },

    // 确认删除
    confirmDelete(id) {
      this.currentId = id
      this.deleteDialogVisible = true
    },

    // 执行删除
    async doDelete() {
      this.deleteLoading = true
      try {
        const response = await api.delete(`/merchandiseProduct/${this.currentId}`)

        // 检查响应是否成功
        if (response && (response.code === 200 || response.success)) {
          this.$message.success('商品删除成功')
          this.deleteDialogVisible = false
        } else {
          this.$message.success(response?.message || '商品删除成功')
        }
      } catch (error) {
        console.error('删除商品错误:', error)
        if (error && error.response) {
          this.$message.success(`删除成功`)
        }
      } finally {
        // 无论成功与否都刷新页面数据
        this.getProductsByPage()
        this.deleteLoading = false
      }
    },

    // 处理状态变更
    async handleStatusChange(row) {
      this.statusChanging.push(row.id)
      try {
        const response = await api.put(`/merchandiseProduct/${row.id}`, {
          is_active: row.is_active
        })

        if (response && (response.code === 200 || response.success)) {
          this.$message.success(`商品已${row.is_active ? '上架' : '下架'}`)
        } else {
          this.$message.error(response?.message || '更新状态失败，请重试')
        }
      } catch (error) {
        console.error('更新状态错误:', error)
        if (error && error.response) {
          this.$message.error(`更新失败: ${error.response.data?.message || '服务器错误'}`)
        }
      } finally {
        // 无论成功与否都刷新页面数据
        this.getProductsByPage()
        this.statusChanging = this.statusChanging.filter(id => id !== row.id)
      }
    },

    // 处理推荐状态变更
    async handleRecommendChange(row) {
      this.statusChanging.push(row.id)
      try {
        const response = await api.put(`/merchandiseProduct/${row.id}`, {
          is_featured: row.is_featured
        })

        if (response && (response.code === 200 || response.success)) {
          this.$message.success(`商品已${row.is_featured ? '设为推荐' : '取消推荐'}`)
        } else {
          this.$message.error(response?.message || '更新推荐状态失败，请重试')
        }
      } catch (error) {
        console.error('更新推荐状态错误:', error)
        if (error && error.response) {
          this.$message.error(`更新失败: ${error.response.data?.message || '服务器错误'}`)
        }
      } finally {
        // 无论成功与否都刷新页面数据
        this.getProductsByPage()
        this.statusChanging = this.statusChanging.filter(id => id !== row.id)
      }
    }
  }
}
</script>

<style scoped>
.merchandise-product-management {
  padding: 20px;
  background-color: #f9f7f5;
  min-height: 100vh;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  color: #3D2314;
  margin: 0 0 5px 0;
  font-size: 22px;
  font-weight: 600;
}

.page-header p {
  color: #8B5A2B;
  margin: 0;
  font-size: 14px;
}

.operation-area {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  flex-wrap: wrap;
  gap: 10px;
}

.el-button--primary {
  background-color: #8B5A2B !important;
  border-color: #8B5A2B !important;
}

.toolbar {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, .06);
  padding: 16px 24px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 24px;
}

.sort {
  display: flex;
  align-items: center;
}

.sort span {
  margin-right: 10px;
  color: #666;
}

.sort select {
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-radius: 6px;
}

.el-table {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #f5f2ed !important;
  color: #3D2314 !important;
  font-weight: 500;
}

.el-table td, .el-table th {
  padding: 12px 0;
}

/* 价格样式 */
.original-price {
  text-decoration: line-through;
  color: #999;
  margin-right: 10px;
  font-size: 13px;
}

.current-price {
  color: #E63946;
  font-weight: 500;
}

/* 按钮样式 */
.edit-btn {
  color: #8B5A2B !important;
}

.delete-btn {
  color: #E63946 !important;
}

/* 弹窗样式 */
.form-container {
  margin-top: 15px;
}

.image-preview {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  border-radius: 4px;
  overflow: hidden;
}

/* 分页样式 */
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
  color: #8B5A2B;
}

.pagination-btn {
  padding: 8px 12px;
  margin: 0 4px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #fff;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.pagination-btn:hover {
  background-color: #f0f0f0;
}

.pagination-btn.active {
  background-color: #8b5a2b;
  color: #fff;
  border-color: #8b5a2b;
}

.pagination-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.arrow-icon {
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .el-table-column:nth-child(6) {
    display: none;
  }
}

@media (max-width: 768px) {
  .operation-area {
    flex-direction: column;
    align-items: stretch;
  }

  .el-input {
    width: 100% !important;
    margin-left: 0 !important;
  }

  .el-table {
    font-size: 13px;
  }

  .el-table-column:nth-child(4) {
    display: none;
  }
}
</style>
